package velox.jcr.mapper.declarative;

import java.util.Map;

import javax.jcr.Node;
import javax.jcr.RepositoryException;

import org.springframework.beans.BeanWrapper;

public class IdMapping implements Mapping {
	public static String CACHE_KEY = "__id";
	
	private String javaProperty;

	private String nameJavaProperty;

	public IdMapping(String javaProperty) {
		this.javaProperty = javaProperty;
	}

	public IdMapping(String javaProperty, String nameJavaProperty) {
		this.javaProperty = javaProperty;
		this.nameJavaProperty = nameJavaProperty;
	}

	public String getJavaProperty() {
		return javaProperty;
	}

	public void read(Node node, BeanWrapper destination) throws RepositoryException {
		destination.setPropertyValue(javaProperty, node.getUUID());
		destination.setPropertyValue(nameJavaProperty, node.getName());
	}

	public void readFromCache(Map<String, Object> cache, BeanWrapper destination) {
		destination.setPropertyValue(javaProperty, ((String[]) cache.get(CACHE_KEY))[0]);
		destination.setPropertyValue(nameJavaProperty, ((String[]) cache.get(CACHE_KEY))[1]);
	}

	public void write(Node node, BeanWrapper object, boolean create) throws RepositoryException {
		object.setPropertyValue(javaProperty, node.getUUID());
	}

	public void writeToCache(Map<String, Object> cache, BeanWrapper object) {
		cache.put(CACHE_KEY, new String[] { (String) object.getPropertyValue(javaProperty), (String) object.getPropertyValue(nameJavaProperty) });
	}

	public String getId(BeanWrapper t) {
		return (String) t.getPropertyValue(javaProperty);
	}

	public String getName(BeanWrapper t) {
		if (nameJavaProperty == null) return null;
		return (String) t.getPropertyValue(nameJavaProperty);
	}

}
